<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/6/26
 * Time: 22:32
 */

namespace Home\Logic;


use Think\Log;

class UserLocationLogic
{
    public function saveLocation($openId,$latitude,$precision,$longitude){
        $map['openid'] =':openid';
        $bind[':openid'] = $openId;
        $model = D('UserLocation');
        $location = $model->where($map)->bind($bind)->find();
        $user = D('Users')->where($map)->bind($bind)->find();
        if($user){
            $data['user_id'] = $user['user_id'];
        }
        $data['latitude'] = $latitude.'';
        $data['precision'] = $precision.'';
        $data['longitude'] = $longitude.'';
        $data['openid'] = $openId.'';
        $data['create_time'] = time();
        Log::write('sql----:'.$model->getLastSql());
        if($location){
            $data['id'] = $location['id'];
            if($location['create_time'] + 43200 <= time()) //半天
            {
                //获取用户地址信息
                $address = $this->getLocation($data['latitude'], $data['longitude']);

                $data['city'] = $address['result']['addressComponent']['city'];

                $data['location'] = $address['result']['formatted_address'].$address['result']['sematic_description'];
                $model->save($data);
            }
        }else{

            $address = $this->getLocation($data['latitude'], $data['longitude']);

            $data['city'] = $address['result']['addressComponent']['city'];

            $data['location'] = $address['result']['formatted_address'].$address['result']['sematic_description'];
            $model->add($data);
        }

    }



    public function getLocation($lat, $lng){

        $url = "http://api.map.baidu.com/geocoder/v2/?ak=xzBzEDKwX4j5uF2Rdy4qbZTu8Mcz3zKq&location=" . $lat . "," . $lng . "&output=json";
        $output = file_get_contents($url);
        $address = json_decode($output, true);
        if($address['status'] == 0)
            return $address;
        else
            return false;

    }
}